package tools.phylip;

import java.util.ArrayList;
import java.util.HashMap;

import tools.fasta.FastaSeq;

public class PhylipSet {

	private ArrayList<FastaSeq> seqs;
	
	public PhylipSet(ArrayList<FastaSeq> in)throws Exception{
		seqs= new ArrayList<FastaSeq>();
		if(in.size()>0){
			HashMap<String, ArrayList<String>> names=new HashMap<String, ArrayList<String>>();
			int maxLength=in.get(0).getSeq().length();
			boolean different_lengths=false,conflicting_names=false;
			String cut_header,tmp;
			for (FastaSeq seq : in) {
				tmp=seq.getHeader().split(" ")[0];
				if(tmp.length()>11){
					cut_header=tmp.substring(1, 11);
				}else{
					cut_header=tmp.substring(1);
					for(;cut_header.length()<10;){
						cut_header+=" ";
					}
				}
				if(names.containsKey(cut_header)){
					conflicting_names=true;
				}else{
					names.put(cut_header, new ArrayList<String>());
				}
				names.get(cut_header).add(seq.getHeader());
				if(maxLength!=seq.getSeq().length()){
					different_lengths=true;
					maxLength=seq.getSeq().length()>maxLength?seq.getSeq().length():maxLength;
				}
				seqs.add(new FastaSeq(cut_header,seq.getSeq()));
			}
			if(different_lengths){
				System.err.println("Transcripts have different lengths... will fill up with -");
				for (FastaSeq seq : seqs) {
					if(seq.getSeq().length()!=maxLength){
						tmp=seq.getSeq();
						while(tmp.length()<maxLength){
							tmp+="-";
						}
						seq.setSeq(tmp);
					}
				}
			}
			if(conflicting_names){
				System.err.println("Some of the following names have the same initial ten letters:");
				for (ArrayList<String> set : names.values()) {
					if(set.size()>1){
						for (String s : set) {
							System.err.println(s);
						}
						System.err.println("---");
					}
				}
			}
		}
	}
	
	public void print2Screen(){
		if(seqs.size()==0){
			System.out.println("   0   0");
		}else{
			boolean printNames=true;
			int length=seqs.get(0).getSeq().length(),j=0,i;
			System.out.println("   "+seqs.size()+"   "+length);
			for(;j<length/50;j++){
				for (FastaSeq seq : seqs) {
					if(printNames){
						System.out.print(seq.getHeader());
						for(i=seq.getHeader().length();i<10;i++){
							System.out.print(" ");
						}
					}else{
						System.out.print("          ");
					}
					for(i=0;i<5;i++){
						System.out.print(" "+seq.getSeq().substring(j*50+i*10, j*50+i*10+10));
					}
					System.out.println();
				}
				printNames=false;
				System.out.println();
			}
			for (FastaSeq seq: seqs) {
				if(printNames){
					System.out.print(seq.getHeader());
					for(i=seq.getHeader().length();i<10;i++){
						System.out.print(" ");
					}
				}else{
					System.out.print("          ");
				}
				for (i = 0; i < (length - j * 50) / 10; i++) {
					System.out.print(" "+seq.getSeq().substring(j*50+i*10, j*50+i*10+10));
				}
				System.out.println(" "+seq.getSeq().substring(j*50+i*10, length));
			}			
		}
	}
}
